//
//  Theme+PPKit.swift
//  PPKit
//
//  Created by iosdevmac201 on 2020/12/25.
//  Copyright © 2020 scoresdata.net. All rights reserved.
//

import UIKit

extension UIView {

    public func setLayerBorderColor(_ color: UIColor) {
        if #available(iOS 13.0, *) {
            if self._privateTheme_value == nil { self._privateTheme_value = MTPrivateThemeView() }
            _privateTheme_value?.traitCollectionChange({ [weak self] in
                guard let self = self else { return }
                self.layer.borderColor = color.resolvedColor(with: self.traitCollection).cgColor
            })
            layer.borderColor = color.resolvedColor(with: traitCollection).cgColor
        } else {
            layer.borderColor = color.cgColor
        }
    }

    public func setLayerShadowColor(_ color: UIColor) {
        if #available(iOS 13.0, *) {
            if self._privateTheme_value == nil { self._privateTheme_value = MTPrivateThemeView() }
            _privateTheme_value?.traitCollectionChange({ [weak self]  in
                guard let self = self else { return }
                self.layer.shadowColor = color.resolvedColor(with: self.traitCollection).cgColor
            })
            layer.shadowColor = color.resolvedColor(with: traitCollection).cgColor
        } else {
            layer.shadowColor = color.cgColor
        }
    }

    public func setLayerBackgroundColor(_ color: UIColor) {
        if #available(iOS 13.0, *) {
            if self._privateTheme_value == nil { self._privateTheme_value = MTPrivateThemeView() }
            _privateTheme_value?.traitCollectionChange({ [weak self]  in
                guard let self = self else { return }
                self.layer.backgroundColor = color.resolvedColor(with: self.traitCollection).cgColor
            })
            layer.backgroundColor = color.resolvedColor(with: traitCollection).cgColor
        } else {
            layer.backgroundColor = color.cgColor
        }
    }

}

extension CAShapeLayer {
    public func setFillColor(_ color: UIColor, with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self] in
                guard let self = self else { return }
                self.fillColor = color.resolvedColor(with: target.traitCollection).cgColor
            })
            fillColor = color.resolvedColor(with: target.traitCollection).cgColor
        } else {
            fillColor = color.cgColor
        }
    }
    
    public func setStrokeColor(_ color: UIColor, with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self] in
                guard let self = self else { return }
                self.strokeColor = color.resolvedColor(with: target.traitCollection).cgColor
            })
            strokeColor = color.resolvedColor(with: target.traitCollection).cgColor
        } else {
            strokeColor = color.cgColor
        }
    }
}

extension CAGradientLayer {
    
    public func setGradientColors(_ colors: [UIColor], with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self] in
                guard let self = self else { return }
                var tempColors = [CGColor]()
                for item in colors {
                    tempColors.append(item.resolvedColor(with: target.traitCollection).cgColor)
                }
                self.colors = tempColors
            })
            var tempColors = [CGColor]()
            for item in colors {
                tempColors.append(item.resolvedColor(with: target.traitCollection).cgColor)
            }
            self.colors = tempColors
        } else {
            self.colors = colors
        }
    }
    
}

extension CALayer {
    public func setBorderColor(_ color: UIColor, with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self] in
                guard let self = self else { return }
                self.borderColor = color.resolvedColor(with: target.traitCollection).cgColor
            })
            borderColor = color.resolvedColor(with: target.traitCollection).cgColor
        } else {
            borderColor = color.cgColor
        }
    }
    
    public func setShadowColor(_ color: UIColor, with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self]  in
                guard let self = self else { return }
                self.shadowColor = color.resolvedColor(with: target.traitCollection).cgColor
            })
            shadowColor = color.resolvedColor(with: target.traitCollection).cgColor
        } else {
            shadowColor = color.cgColor
        }
    }

    public func setBackgroundColor(_ color: UIColor, with target: UIView) {
        if #available(iOS 13.0, *) {
            if target._privateTheme_value == nil { target._privateTheme_value = MTPrivateThemeView() }
            target._privateTheme_value?.traitCollectionChange({ [weak self]  in
                guard let self = self else { return }
                self.backgroundColor = color.resolvedColor(with: target.traitCollection).cgColor
            })
            backgroundColor = color.resolvedColor(with: target.traitCollection).cgColor
        } else {
            backgroundColor = color.cgColor
        }
    }
    
    
}


class MTPrivateThemeView: UIView {
    
    typealias TraitCollectionCallBack = () -> Void
    
    private var callbackList:[TraitCollectionCallBack?] = []
    
    convenience init() {
        self.init(frame: .zero)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func traitCollectionChange(_ callback: TraitCollectionCallBack?) {
        callbackList.append(callback)
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if #available(iOS 13.0, *) {
            //这里只关系颜色是否发生了改变
            if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
                for callback in callbackList {
                    callback?()
                }
            }
        }
    }
    
}

extension UIView {
    
    private struct RuntimeKey {
        static let mt_privateThemeview_key = UnsafeRawPointer.init(bitPattern: "mt_privateThemeViewKey".hashValue)
        /// ...其他Key声明
    }
    
    var _privateTheme_value : MTPrivateThemeView? {
        get {
            return objc_getAssociatedObject(self, UIView.RuntimeKey.mt_privateThemeview_key!) as? MTPrivateThemeView
        }
        set{
            if let newValue = newValue, _privateTheme_value != newValue {
                _privateTheme_value?.removeFromSuperview()
                newValue.isHidden = true
                insertSubview(newValue, at: 0)
                objc_setAssociatedObject(self, UIView.RuntimeKey.mt_privateThemeview_key!, newValue, .OBJC_ASSOCIATION_ASSIGN)
            }
        }
    }
    
}
